<!DOCTYPE html>
<html>
<head>
    <title>WebSocket 客户端</title>
</head>
<body>
    <h1>WebSocket 客户端</h1>
    <form action="" onsubmit="sendMessage(event)">
        <input type="text" id="targetId" placeholder="Target Client ID" autocomplete="off"/>
        <input type="text" id="messageText" placeholder="Message" autocomplete="off"/>
        <button>Send</button>
    </form>
    <ul id='messages'></ul>
    <input type="file" id="audioFile" accept="audio/*"/>
    <button onclick="sendAudio()">Send Audio</button>
    <script>
        var ws;

        function connect() {
            var uniqueId = document.getElementById("uniqueId").value;
            ws = new WebSocket("ws://118.145.156.248:8000/ws");

            ws.onopen = function(event) {
                console.log("Connected to WebSocket server.");
                // 发送设备的唯一ID
                ws.send(uniqueId);
            };

            ws.onmessage = function(event) {
                var messages = document.getElementById('messages');
                var message = document.createElement('li');
                var content = document.createTextNode(event.data);
                message.appendChild(content);
                messages.appendChild(message);
            };

            ws.onclose = function(event) {
                console.log("Disconnected from WebSocket server.");
            };
        }

        function sendMessage(event) {
            var targetId = document.getElementById("targetId").value;
            var messageText = document.getElementById("messageText").value;
            var message = JSON.stringify({target: targetId, content: messageText});
            ws.send(message);
            event.preventDefault();
        }

        function sendAudio() {
            var file = document.getElementById("audioFile").files[0];
            if (!file) {
                alert("Please select an audio file first.");
                return;
            }

            var reader = new FileReader();
            reader.onload = function(event) {
                var arrayBuffer = event.target.result;
                var bytes = new Uint8Array(arrayBuffer);
                ws.send(bytes);
                ws.send("EOF");
            };
            reader.readAsArrayBuffer(file);
        }
    </script>
    <input type="text" id="uniqueId" placeholder="Enter Unique ID" autocomplete="off"/>
    <button onclick="connect()">Connect</button>
</body>
</html>
